package cn.Controller;

import cn.VerifyConsumeQueue.VerifyConsumeQueue;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

@Controller
public class ThirdController {

    ReadWriteLock readWriteLock = new ReentrantReadWriteLock();

    @ResponseBody
    @RequestMapping("/testcp")
    public synchronized String testcp(String code) {

        LinkedBlockingQueue linkedBlockingQueue = VerifyConsumeQueue.getLinkedBlockingQueue();

        try {
//            readWriteLock.writeLock().lock();
            linkedBlockingQueue.put(code);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("Provider : code : "+code);
        Thread thread = new Thread(new ConsumerThread(),"核销处理线程");
        thread.start();

        synchronized (code){
            try {
                code.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        System.out.println("生产者获得锁");
        return "success : "+code;
    }
}

class Consumer{

    private static volatile String codeStr = "123";
    private static volatile int count = 0;

    public synchronized void consume() {
        LinkedBlockingQueue linkedBlockingQueue = VerifyConsumeQueue.getLinkedBlockingQueue();
        String  code = null;
        try {
            code = (String) linkedBlockingQueue.take();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        if (code.equals(codeStr)) {
            if(count<1)
            System.out.println("code 123 had been Consumer ==================================");
            count++;
        }

        System.out.println("Consumer : code : "+code);
 /*       try {
//            Thread.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }*/
        synchronized (code){
            code.notify();
        }
    }
}

class ConsumerThread implements Runnable{

    @Override
    public void run() {
        Consumer consumer = new Consumer();
        consumer.consume();

    }
}